package team.you.change.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传工具类
 */
public class UpUtils {

	public static String fileUp(MultipartFile file, HttpServletRequest request){
		String[] split = file.getOriginalFilename().split("[.]"); //分割完整文件名
		String endName = split[split.length - 1]; //获取文件后缀
		String newName = UUID.randomUUID().toString().replace("-", ""); //生成一个随机文件名
		String path = "";
		if("png".equals(endName) || "jpg".equals(endName)){
			path = request.getSession().getServletContext().getRealPath("/WEB-INF/img/") + newName + "." + endName; //拼接文件路径
		}else{
			path = request.getSession().getServletContext().getRealPath("/WEB-INF/video/") + newName + "." + endName;
		}
		try {
			file.transferTo(new File(path)); //写入文件到服务器
			return "/Class/img/" + newName + "." + endName;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}
